﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Logger.Core
{
    /// <summary>
    ///  Function:提供一组日志的方法
    ///  Remark:日志记录方法可以使用第三方组件,如log4net
    ///  Author:zhangzhanling
    ///  Blogs:www.cnblogs.com/lori
    ///  </summary>
    internal class Log4Logger : LoggerBase
    {
        /// <summary>
        /// log4net配置文件路径
        /// </summary>
        static string _logConfig = System.Web.HttpContext.Current.Server.MapPath("/log4net.config");

        static Log4Logger()
        {
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(_logConfig));
        }

        #region Prviate Methods
        /// <summary>
        /// 写日志方法
        /// </summary>
        /// <param name="message"></param>
        /// <param name="fileName"></param>
        protected override void InputLogger(string message, string fileName)
        {
            string filePath = MvcUrl + fileName;
            var iLog = log4net.LogManager.GetLogger("Core.Logger");
            ChangeLog4netLogFileName(iLog, filePath, message);
        }

        private void ChangeLog4netLogFileName(log4net.ILog iLog, string filePath, string message)
        {
            log4net.Core.LogImpl logImpl = iLog as log4net.Core.LogImpl;
            if (logImpl != null)
            {
                var ac = ((log4net.Repository.Hierarchy.Logger)logImpl.Logger).Appenders;
                var rfa = ac[0] as log4net.Appender.RollingFileAppender;
                if (rfa != null)
                {
                    string dir = filePath.Substring(0, filePath.LastIndexOf("\\"));
                    if (!System.IO.Directory.Exists(dir))
                    {
                        System.IO.Directory.CreateDirectory(dir);
                    }
                    rfa.File = filePath;
                    // 更新Writer属性
                    rfa.Writer = new System.IO.StreamWriter(rfa.File, rfa.AppendToFile, rfa.Encoding);
                    rfa.Writer.WriteLine(message);
                    rfa.Writer.Close();
                    rfa.Writer.Dispose();
                    rfa.Close();

                }

            }
        }

        #endregion

    }
}
